package com.saasitems.admin.web.restcontroller;

import com.saasitems.admin.model.TemplateInfo;
import com.saasitems.admin.service.TemplateInfoService;
import com.saasitems.common.utils.PropertiesUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/4/19.
 */
@RestController
public class FileInfoController {

    @Autowired
    private TemplateInfoService templateInfoService;

    private String getTemplName(String fileName) {
        if (fileName.length() < 12) {
            return "";
        }
        int last = fileName.lastIndexOf('.');
        if (last < 0) {
            return "";
        }
        return fileName.substring(last - 8, last);
    }

    @RequestMapping(value = "rest/file/scan", method = RequestMethod.POST)
    @ResponseBody
    public Object scanFolder() {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            ret.put("status", "success");
            String path = PropertiesUtil.newInstance().getStringByKey("SCAN.FOLDER");;
            String url = PropertiesUtil.newInstance().getStringByKey("SCAN.URL");;
            File file = new File(path);
            File[] files = file.listFiles();
            if (files != null && files.length > 0) {
                String fileName = files[0].getName();
                String templ = getTemplName(fileName);
                TemplateInfo info = this.templateInfoService.getInfo(templ);
                ret.put("context", info.getContext());
                url = url + "/" + fileName;
                ret.put("url", url);
                ret.put("fileName", fileName);
            } else {
                ret.put("url", "");
                ret.put("fileName", "");
                ret.put("context", "");
            }

        } catch (Exception e) {
            e.printStackTrace();
            ret.put("status", "error");
        }
        return ret;
    }

    @RequestMapping(value = "rest/file/delete", method = RequestMethod.POST)
    @ResponseBody
    public Object deleteFile(String filename) {
        Map<String, Object> ret = new HashMap<String, Object>();
        try {
            String path = PropertiesUtil.newInstance().getStringByKey("SCAN.FOLDER");;
            String url = PropertiesUtil.newInstance().getStringByKey("SCAN.URL");;
            File file = new File(path + File.separatorChar + filename);
            if (file.delete()) {
                ret.put("status", "success");
            } else {
                ret.put("status", "error");
            }
        } catch (Exception e) {
            ret.put("status", "error");
        }
        return ret;
    }
}
